<?php
namespace app\controllers;
use app\models\CourseModel;
use wlcat\src\plugin\UploadFile;

//课程
class CourseController extends AdminController {
    public function index($id = null)
    {
        $list = (new CourseModel())->selectAll();
        $this->assign('list', $list);
        $this->display();
    }
    public function view($id = null)
    {
        $item = (new CourseModel)->select($id);

        $this->assign('info', $item);
        $this->display();
    }

    public function add()
    {
        $this->display();
    }
    public function insert()
    {
        $name           = $this->request->input('post.name');
        $description    = $this->request->input('post.description');
        $photo          = $this->upload();
        (new CourseModel())->add(array(
            'name'          => $name,
            'description'   => $description,
            'photo'         => $photo ? $photo : ""
        ));
        $this->success('插入成功', admin_url('course/index'), 1);
    }

    public function update()
    {
        $id = $this->request->input('post.id');
        if (!intval($id) > 0)
        {
            echo 'id错误';
            die;
        }

        $data['name']           = $this->request->input('post.name');
        $data['description']    = $this->request->input('post.description');
        $photo                  = $this->upload();
        if ($photo)
        {
            $data['photo'] = $photo;
        }
        (new CourseModel())->update($id, $data);
        $this->success('更新成功', admin_url('course/index'), 1);
    }

    public function upload()
    {
        $upload = new UploadFile();// 实例化上传类
        $upload->maxSize  = 3145728 ;// 设置附件上传大小
        $upload->allowExts  = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $path=date("Ym").'/';
        $upload->savePath =  APP_PATH.'public/Data/photo/'.$path;// 设置附件上传目录
        if(!file_exists($upload->savePath)){
            mkdir($upload->savePath);
        }
        if(!$upload->upload()) {// 上传错误提示错误信息
            echo $upload->getErrorMsg();die;
            return false;
        }else{// 上传成功 获取上传文件信息
            $info =  $upload->getUploadFileInfo();
            $info = $info[0];
           return trim($info['savepath'], APP_PATH.'public')."/".$info['savename'];
        }
    }

    public function destroy($id)
    {
        $item = (new CourseModel)->select($id);
        @unlink('.'.$item['photo']);
        (new CourseModel())->delete($id);
        $this->success('删除成功', admin_url('course/index'), 1);
    }
}